<template>
  <div class="content-card">
    <div class="page-header">
      <h2>订单详情</h2>
      <el-button @click="handleBack">返回列表</el-button>
    </div>
    
    <!-- 订单基本信息 -->
    <el-card class="order-info">
      <template #header>
        <div class="card-header">
          <span>订单基本信息</span>
        </div>
      </template>
      
      <div class="info-row">
        <div class="info-item">
          <label>订单编号：</label>
          <span>{{ orderDetail.orderNo }}</span>
        </div>
        <div class="info-item">
          <label>订单状态：</label>
          <el-tag :type="getStatusTagType(orderDetail.status)">
            {{ getStatusText(orderDetail.status) }}
          </el-tag>
        </div>
        <div class="info-item">
          <label>下单时间：</label>
          <span>{{ orderDetail.orderTime }}</span>
        </div>
        <div class="info-item">
          <label>支付时间：</label>
          <span>{{ orderDetail.payTime || '未支付' }}</span>
        </div>
      </div>
      
      <div class="info-row">
        <div class="info-item">
          <label>支付方式：</label>
          <span>{{ getPaymentMethodText(orderDetail.paymentMethod) }}</span>
        </div>
        <div class="info-item">
          <label>支付流水号：</label>
          <span>{{ orderDetail.paymentNo || '无' }}</span>
        </div>
        <div class="info-item">
          <label>发货时间：</label>
          <span>{{ orderDetail.shipTime || '未发货' }}</span>
        </div>
        <div class="info-item">
          <label>完成时间：</label>
          <span>{{ orderDetail.completeTime || '未完成' }}</span>
        </div>
      </div>
    </el-card>
    
    <!-- 用户信息 -->
    <el-card class="user-info">
      <template #header>
        <div class="card-header">
          <span>用户信息</span>
        </div>
      </template>
      
      <div class="info-row">
        <div class="info-item">
          <label>用户ID：</label>
          <span>{{ orderDetail.userId }}</span>
        </div>
        <div class="info-item">
          <label>用户名：</label>
          <span>{{ orderDetail.userName }}</span>
        </div>
        <div class="info-item">
          <label>联系电话：</label>
          <span>{{ orderDetail.phone }}</span>
        </div>
      </div>
    </el-card>
    
    <!-- 收货信息 -->
    <el-card class="address-info">
      <template #header>
        <div class="card-header">
          <span>收货信息</span>
        </div>
      </template>
      
      <div class="info-row">
        <div class="info-item">
          <label>收货人：</label>
          <span>{{ orderDetail.receiverName }}</span>
        </div>
        <div class="info-item">
          <label>联系电话：</label>
          <span>{{ orderDetail.receiverPhone }}</span>
        </div>
      </div>
      <div class="info-row">
        <div class="info-item full-width">
          <label>收货地址：</label>
          <span>{{ orderDetail.receiverAddress }}</span>
        </div>
      </div>
      <div class="info-row" v-if="orderDetail.receiverRemark">
        <div class="info-item full-width">
          <label>备注：</label>
          <span>{{ orderDetail.receiverRemark }}</span>
        </div>
      </div>
    </el-card>
    
    <!-- 商品信息 -->
    <el-card class="product-info">
      <template #header>
        <div class="card-header">
          <span>商品信息</span>
        </div>
      </template>
      
      <el-table :data="orderDetail.orderItems" style="width: 100%">
        <el-table-column prop="productName" label="商品名称" min-width="200" />
        <el-table-column prop="productSku" label="商品规格" width="150" />
        <el-table-column prop="quantity" label="数量" width="80" />
        <el-table-column prop="price" label="单价" width="100" formatter="formatPrice" />
        <el-table-column prop="totalPrice" label="小计" width="100" formatter="formatPrice" />
      </el-table>
    </el-card>
    
    <!-- 支付信息 -->
    <el-card class="payment-info">
      <template #header>
        <div class="card-header">
          <span>支付信息</span>
        </div>
      </template>
      
      <div class="payment-summary">
        <div class="summary-item">
          <label>商品总价：</label>
          <span>{{ formatPrice(orderDetail.productTotalAmount) }}</span>
        </div>
        <div class="summary-item">
          <label>运费：</label>
          <span>{{ formatPrice(orderDetail.shippingFee) }}</span>
        </div>
        <div class="summary-item">
          <label>优惠金额：</label>
          <span class="text-danger">{{ formatPrice(orderDetail.discountAmount) }}</span>
        </div>
        <div class="summary-item total">
          <label>实付金额：</label>
          <span>{{ formatPrice(orderDetail.totalAmount) }}</span>
        </div>
      </div>
    </el-card>
    
    <!-- 订单操作 -->
    <div class="order-actions" v-if="orderDetail.status === 1">
      <el-button type="primary" @click="handleShipOrder">发货</el-button>
    </div>
    
    <div class="order-actions" v-if="orderDetail.status === 0">
      <el-button type="danger" @click="handleCancelOrder">取消订单</el-button>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { orderApi } from '../../api/order.js'

export default {
  name: 'OrderDetail',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const loading = ref(false)
    const orderDetail = ref({
      orderNo: '',
      status: 0,
      orderTime: '',
      payTime: '',
      shipTime: '',
      completeTime: '',
      paymentMethod: 0,
      paymentNo: '',
      userId: '',
      userName: '',
      phone: '',
      receiverName: '',
      receiverPhone: '',
      receiverAddress: '',
      receiverRemark: '',
      productTotalAmount: 0,
      shippingFee: 0,
      discountAmount: 0,
      totalAmount: 0,
      orderItems: []
    })
    
    // 格式化价格
    const formatPrice = (price) => {
      return `¥${price.toFixed(2)}`
    }
    
    // 获取支付方式文本
    const getPaymentMethodText = (method) => {
      const methodMap = {
        1: '支付宝',
        2: '微信支付',
        3: '银行卡'
      }
      return methodMap[method] || '未知'
    }
    
    // 获取订单状态文本
    const getStatusText = (status) => {
      const statusMap = {
        0: '待支付',
        1: '待发货',
        2: '待收货',
        3: '已完成',
        4: '已取消'
      }
      return statusMap[status] || '未知'
    }
    
    // 获取订单状态标签类型
    const getStatusTagType = (status) => {
      const typeMap = {
        0: 'warning',
        1: 'primary',
        2: 'info',
        3: 'success',
        4: 'danger'
      }
      return typeMap[status] || 'default'
    }
    
    // 获取订单详情
    const getOrderDetail = async () => {
      loading.value = true
      try {
        const orderId = route.params.id
        
        // 模拟API请求，使用mock数据
        setTimeout(() => {
          orderDetail.value = generateMockDetail(orderId)
          loading.value = false
        }, 500)
        
        // 实际API调用代码（目前注释掉）
        // const response = await orderApi.getOrderDetail(orderId)
        // orderDetail.value = response.data
        // loading.value = false
      } catch (error) {
        console.error('获取订单详情失败:', error)
        ElMessage.error('获取订单详情失败')
        loading.value = false
      }
    }
    
    // 生成模拟订单详情数据
    const generateMockDetail = (orderId) => {
      // 随机生成订单状态
      const status = Math.floor(Math.random() * 5)
      const paymentMethod = Math.floor(Math.random() * 3) + 1
      
      // 模拟订单项
      const orderItems = []
      const itemCount = Math.floor(Math.random() * 3) + 1
      let productTotalAmount = 0
      
      for (let i = 0; i < itemCount; i++) {
        const price = Math.floor(Math.random() * 1000) + 100
        const quantity = Math.floor(Math.random() * 5) + 1
        const totalPrice = price * quantity
        productTotalAmount += totalPrice
        
        orderItems.push({
          productId: Math.floor(Math.random() * 1000) + 1,
          productName: `测试商品${Math.floor(Math.random() * 1000)}`,
          productSku: `颜色：${['红', '蓝', '黑', '白'][Math.floor(Math.random() * 4)]}，尺码：${['S', 'M', 'L', 'XL'][Math.floor(Math.random() * 4)]}`,
          quantity: quantity,
          price: price,
          totalPrice: totalPrice
        })
      }
      
      // 计算运费和优惠金额
      const shippingFee = productTotalAmount > 500 ? 0 : 10
      const discountAmount = Math.floor(productTotalAmount * 0.1)
      const totalAmount = productTotalAmount + shippingFee - discountAmount
      
      // 根据状态设置相应的时间
      const now = new Date()
      const orderTime = new Date(now.getTime() - Math.floor(Math.random() * 24 * 60 * 60 * 1000))
      let payTime = ''
      let shipTime = ''
      let completeTime = ''
      
      if (status > 0) {
        payTime = new Date(orderTime.getTime() + Math.floor(Math.random() * 2 * 60 * 60 * 1000))
      }
      
      if (status > 1) {
        shipTime = new Date(payTime.getTime() + Math.floor(Math.random() * 24 * 60 * 60 * 1000))
      }
      
      if (status > 2) {
        completeTime = new Date(shipTime.getTime() + Math.floor(Math.random() * 7 * 24 * 60 * 60 * 1000))
      }
      
      return {
        id: orderId,
        orderNo: `ORD-${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}-${String(orderId).padStart(4, '0')}`,
        status: status,
        orderTime: orderTime.toLocaleString(),
        payTime: payTime ? payTime.toLocaleString() : '',
        shipTime: shipTime ? shipTime.toLocaleString() : '',
        completeTime: completeTime ? completeTime.toLocaleString() : '',
        paymentMethod: paymentMethod,
        paymentNo: status > 0 ? `PAY-${Math.floor(Math.random() * 100000000)}` : '',
        userId: Math.floor(Math.random() * 10000) + 1,
        userName: `用户${Math.floor(Math.random() * 10000)}`,
        phone: `138${Math.floor(Math.random() * 100000000).toString().padStart(8, '0')}`,
        receiverName: ['张三', '李四', '王五', '赵六'][Math.floor(Math.random() * 4)],
        receiverPhone: `139${Math.floor(Math.random() * 100000000).toString().padStart(8, '0')}`,
        receiverAddress: `北京市朝阳区${Math.floor(Math.random() * 100)}号院${Math.floor(Math.random() * 10)}号楼${Math.floor(Math.random() * 300)}室`,
        receiverRemark: Math.random() > 0.5 ? '尽快发货' : '',
        productTotalAmount: productTotalAmount,
        shippingFee: shippingFee,
        discountAmount: discountAmount,
        totalAmount: totalAmount,
        orderItems: orderItems
      }
    }
    
    // 处理发货
    const handleShipOrder = async () => {
      try {
        // 模拟发货请求
        setTimeout(() => {
          ElMessage.success('发货成功')
          getOrderDetail() // 重新获取订单详情
        }, 500)
        
        // 实际API调用代码（目前注释掉）
        // await orderApi.shipOrder(orderDetail.value.id)
        // ElMessage.success('发货成功')
        // getOrderDetail() // 重新获取订单详情
      } catch (error) {
        console.error('发货失败:', error)
        ElMessage.error('发货失败')
      }
    }
    
    // 处理取消订单
    const handleCancelOrder = async () => {
      ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 模拟取消请求
          setTimeout(() => {
            ElMessage.success('订单取消成功')
            getOrderDetail() // 重新获取订单详情
          }, 500)
          
          // 实际API调用代码（目前注释掉）
          // await orderApi.cancelOrder(orderDetail.value.id)
          // ElMessage.success('订单取消成功')
          // getOrderDetail() // 重新获取订单详情
        } catch (error) {
          console.error('取消订单失败:', error)
          ElMessage.error('取消订单失败')
        }
      }).catch(() => {
        // 取消操作
      })
    }
    
    // 返回列表
    const handleBack = () => {
      router.push('/order/list')
    }
    
    // 初始化数据
    onMounted(() => {
      getOrderDetail()
    })
    
    return {
      loading,
      orderDetail,
      formatPrice,
      getPaymentMethodText,
      getStatusText,
      getStatusTagType,
      handleShipOrder,
      handleCancelOrder,
      handleBack
    }
  }
}
</script>

<style scoped lang="scss">
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.order-info,
.user-info,
.address-info,
.product-info,
.payment-info {
  margin-bottom: 20px;
  
  .card-header {
    font-weight: bold;
  }
  
  .info-row {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 10px;
    
    .info-item {
      margin-right: 30px;
      margin-bottom: 10px;
      
      &.full-width {
        width: 100%;
        margin-right: 0;
      }
      
      label {
        color: var(--text-secondary);
        margin-right: 10px;
      }
    }
  }
  
  .payment-summary {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    
    .summary-item {
      margin-bottom: 10px;
      
      label {
        margin-right: 10px;
      }
      
      &.total {
        font-size: 16px;
        font-weight: bold;
        margin-top: 20px;
      }
    }
  }
}

.order-actions {
  margin-top: 20px;
  text-align: right;
}

.text-danger {
  color: var(--danger-color);
}
</style>